package com.ly.demo.weixin.req;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@Data
@Slf4j
public class ConversationStreamListener extends EventSourceListener {

    public ConversationStreamListener(SseEmitter emitter) {
        this.context = emitter;
    }

    /**
     * 请求ID
     */
    protected String requestId;

    private SseEmitter context;


    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        log.info("ConversationStreamListener.onClosed: requestId={}, eventSource={}", requestId, eventSource);
        try {
            context.send(SseEmitter.event().data("end"));
        } catch (Exception e) {
            log.error("ConversationStreamListener onClose e={}", e);
        }
        log.info("[ConversationStreamListener] 客户端已关闭");
        context.complete();
    }

    @Override
    public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
        log.info("ConversationStreamListener.onEvent: type:{},data={}", type,data);
        try {
            context.send(SseEmitter.event().data(data));
        } catch (IOException e) {
            log.error("ConversationStreamListener onEvent {}", e);
            context.complete();
        }

    }

    @Override
    public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
        log.error("ConversationStreamListener.onFailure: response={}", response);
        context.complete();
        log.error("ConversationStreamListener.onFailure: e {}", t);
    }

    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        log.info("ConversationStreamListener.onOpen: response={}", response);
    }

}
